#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Word2MD 项目启动器
提供统一的入口点来运行项目的不同组件
"""

import sys
import os
import subprocess
import argparse
from pathlib import Path


def get_python_path():
    """获取Python解释器路径"""
    # 优先使用虚拟环境
    venv_path = Path("word2md_env")

    if venv_path.exists():
        if os.name == 'nt':  # Windows
            python_path = venv_path / "Scripts" / "python.exe"
        else:  # Unix-like
            python_path = venv_path / "bin" / "python"

        if python_path.exists():
            return str(python_path)

    # 回退到系统Python
    return sys.executable


def run_gui():
    """启动图形界面"""
    print("🚀 启动Word转Markdown GUI界面...")
    python_path = get_python_path()
    subprocess.run([python_path, "word2md_gui.py"])


def run_test():
    """运行测试"""
    print("🧪 运行转换器测试...")
    python_path = get_python_path()
    subprocess.run([python_path, "test_converter.py"])


def run_convert(file_path, batch=False, use_pandoc=None):
    """运行命令行转换"""
    print(f"🔄 开始转换: {file_path}")
    python_path = get_python_path()

    cmd = [python_path, "word2md.py", file_path]

    if batch:
        cmd.append("--batch")

    if use_pandoc is not None:
        if use_pandoc:
            cmd.extend(["--engine", "pandoc"])
        else:
            cmd.extend(["--engine", "builtin"])

    subprocess.run(cmd)


def run_format_fixer(file_path):
    """运行格式修复工具"""
    print(f"🔧 修复格式: {file_path}")
    python_path = get_python_path()
    subprocess.run([python_path, "doc_format_fixer.py", file_path])


def setup_environment():
    """设置开发环境"""
    print("⚙️  设置开发环境...")

    # 检查虚拟环境
    venv_path = Path("word2md_env")
    if not venv_path.exists():
        print("📦 创建虚拟环境...")
        subprocess.run([sys.executable, "-m", "venv", "word2md_env"])

    # 安装依赖
    python_path = get_python_path()
    print("📚 安装依赖包...")
    subprocess.run([python_path, "-m", "pip", "install", "-r", "requirements.txt"])

    print("✅ 环境设置完成!")


def show_menu():
    """显示主菜单"""
    print("\n" + "="*50)
    print("     Word转Markdown工具 - 项目启动器")
    print("="*50)
    print("请选择要执行的操作:")
    print("1. 启动GUI界面")
    print("2. 运行测试")
    print("3. 命令行转换")
    print("4. 批量转换")
    print("5. 格式修复工具")
    print("6. 设置开发环境")
    print("0. 退出")
    print("-"*50)


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="Word2MD 项目启动器")
    parser.add_argument("--gui", action="store_true", help="启动GUI界面")
    parser.add_argument("--test", action="store_true", help="运行测试")
    parser.add_argument("--setup", action="store_true", help="设置开发环境")
    parser.add_argument("--convert", type=str, help="转换指定文件")
    parser.add_argument("--batch", action="store_true", help="批量转换模式")
    parser.add_argument("--fix", type=str, help="修复指定Markdown文件格式")
    parser.add_argument("--pandoc", action="store_true", help="强制使用Pandoc")
    parser.add_argument("--builtin", action="store_true", help="强制使用内置转换器")

    args = parser.parse_args()

    # 处理命令行参数
    if args.gui:
        run_gui()
        return

    if args.test:
        run_test()
        return

    if args.setup:
        setup_environment()
        return

    if args.convert:
        use_pandoc = None
        if args.pandoc:
            use_pandoc = True
        elif args.builtin:
            use_pandoc = False
        run_convert(args.convert, args.batch, use_pandoc)
        return

    if args.fix:
        run_format_fixer(args.fix)
        return

    # 如果没有参数，显示交互式菜单
    while True:
        show_menu()
        try:
            choice = input("请输入选择 (0-6): ").strip()

            if choice == "0":
                print("👋 再见!")
                break
            elif choice == "1":
                run_gui()
            elif choice == "2":
                run_test()
            elif choice == "3":
                file_path = input("请输入Word文档路径: ").strip()
                if file_path:
                    run_convert(file_path)
            elif choice == "4":
                dir_path = input("请输入包含Word文档的目录路径: ").strip()
                if dir_path:
                    run_convert(dir_path, batch=True)
            elif choice == "5":
                file_path = input("请输入Markdown文件路径: ").strip()
                if file_path:
                    run_format_fixer(file_path)
            elif choice == "6":
                setup_environment()
            else:
                print("❌ 无效选择，请重新输入")

        except KeyboardInterrupt:
            print("\n👋 再见!")
            break
        except Exception as e:
            print(f"❌ 发生错误: {e}")


if __name__ == "__main__":
    main()
